<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Wechats;
use app\common\model\Members;
use app\common\model\Attachment;
use think\Session;
use think\Db;
use app\common\model\Messages;
/**
 * 首页接口
 */
class Async extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    /**
     * 获取微信粉丝管理
     *
     */
    public function members($wechat_id=null,$next_openid=null)
    {
        $param = file_get_contents("php://input");
        $param = json_decode($param,true);
        if(isset($param['openids']) && !empty($param['openids'])){
            // 批量请求微信用户
            $members = [];
            $openids = [];
            $count = count($param['openids']);
            $i=0;
            $k=0;
            foreach ($param['openids'] as $key => $openid) {
                $openids[$i][] = ['openid' => $openid];
                $k++;
                if($k==100){
                    $i++;
                    $k=0;
                }
            }
            foreach($openids as $openidss){
                $result = (new \app\common\logic\Wechat)->weObj($param['wechat_id'])->getUserInfoList(['user_list'=>$openidss]);
                if(isset($result['user_info_list']) && is_array($result['user_info_list'])){
                    foreach ($result['user_info_list'] as $member) {
                        $member['update_at'] = time();
                        $result = Members::where('openid',$member['openid'])->update($member);
                        if(!$result){
                            $member['wechat_id'] = $param['wechat_id'];
                            $members[] = $member;
                        }
                    }
                }
            }
            // 添加用户到数据库中
            if(is_array($members) && !empty($members)){
                 Members::insertAll($members,true,true);
            }
        }
    }
    // 同步微信自定义菜单
    public function menu(){
        $param = file_get_contents("php://input");
        $param = json_decode($param,true);
        if(isset($param['wechat_id']) && $param['wechat_id'] > 0){
            if(isset($param['wechatId']) && $param['wechatId'] > 0 && $param['wechatId'] != $param['wechat_id']){
                db('wx_menu')->where('wechat_id',$param['wechatId'])->delete();
                $cpMenu = db('wx_menu')->where('wechat_id',$param['wechat_id'])->where('pid',0)->select();
                if(!empty($cpMenu)){
                    $base=[];
                    $sub = [];
                    foreach ($cpMenu as $key => $item) {
                        $item['wechat_id'] = $param['wechatId'];
                        $subMenus = db('wx_menu')->where('pid',$item['menu_id'])->where('wechat_id',$param['wechat_id'])->select();
                        $sub = [];
                        if($subMenus){
                            unset($item['menu_id']);
                            $pid = db('wx_menu')->insert($item,true,true);
                            foreach($subMenus as $subMenu){
                                $option = json_decode($subMenu['options'],true);
                                if(isset($option['type']) && $option['type'] == 'image'){
                                    $media_id = (new Attachment)->getMedia_id($option['image'],$param['wechat_id']);
                                    $option['media_id'] = $media_id;
                                }
                                // 图文
                                if(isset($option['type']) && $option['type'] == 'mpnews'){

                                }
                                $item['options'] = json_encode($option);
                                $subMenu['pid'] = $pid;
                                $subMenu['wechat_id'] = $param['wechatId'];
                                unset($subMenu['menu_id']);
                                $sub[] = $subMenu;
                            }
                            db('wx_menu')->insertAll($sub);
                        }else{
                            $option = json_decode($item['options'],true);
                            if(isset($option['type']) && $option['type'] == 'image'){
                                $media_id = (new Attachment)->getMedia_id($option['image'],$param['wechat_id']);
                                $option['media_id'] = $media_id;
                            }
                            // 图文
                            if(isset($option['type']) && $option['type'] == 'mpnews'){

                            }
                            $item['options'] = json_encode($option);
                            unset($item['menu_id']);
                            db('wx_menu')->insert($item);
                        }
                    }
                }
                // 微信生成
                $result = (new \app\common\logic\Wechat)->createMenu($param['wechatId']);
                if($result !== true){
                    \app\common\model\Logs::addLog("%s自定义菜单失败",$result,$param['wechatId'],"async/menu");
                }
            }
        }
    }
    // 关注回复
    public function follow(){
        $param = file_get_contents("php://input");
        $param = json_decode($param,true);
        if($param['wechatId'] != $param['wechat_id']){
            $row = db('replys')->where('wechat_id',$param['wechat_id'])->find();
            if(empty($row)){
                return '';
            }
            $row['wechat_id'] = $param['wechatId'];
            $row['type'] = isset($row['type']) ? $row['type'] : 'follow';
            db('replys')->insert($row,true,true);
        }
        die('FINISH...');
    }
    // 同步关键字
    public function keywork(){
        $param = file_get_contents("php://input");

        //$param = '{"wechat_id":"1","ids":"6,2,1","wechatId":"2"}';
        $param = json_decode($param,true);
        if(isset($param['type']) && $param['type'] == 'cp'){
            $ids = db('keywords')->where('wechat_id',$param['wechat_id'])->column('id');
            if(empty($ids)){
                return '';
            }
            $param['ids'] = implode(",", $ids);
        }
        if(isset($param['ids']) && !empty($param['ids'])){
            $ids = explode(",", $param['ids']);
        }
        $ids = is_array($ids) ? $ids : [];
        $keyworks = db('keywords')->where('id','in',$ids)->select();
        if(!empty($keyworks) && $param['wechatId'] != $param['wechat_id']){
            foreach($keyworks as $row){
                $items = (new \app\common\model\Keywords)->getKeywordAttr($param['wechat_id'],$row,$param['wechat_id']);
                db('keywork_wechat')->insert(['wechat_id'=>$param['wechatId'],'keywork_id'=>$row['id']],true,true);
                db('keyword_mate')->where(['wechat_id'=>$param['wechatId'],'keyword_id'=>$row['id']])->delete();

                if(is_array($items)){
                    $base = [];
                    foreach($items as $keyword){
                        $base[] = ['wechat_id'=>$param['wechatId'],'keyword'=>$keyword,'keyword_id'=>$row['id']];
                    }
                    db('keyword_mate')->insertAll($base,true,true);
                }
            }

        }
        die("FINISH....");
    }
    // 发生消息
    public function message(){
        $param = file_get_contents("php://input");
        $param = json_decode($param,true);
        if(isset($param['wechat_id']) && $param['wechatId']){
            if($param['wechat_id'] != $param['wechatId']){
                $data = $param['data'];
                $data['wechat_id'] = $param['wechatId'];
                // 发送文字内容
                if($data['type'] == 'text'){
                    $mess['text'] = ['content'=>$data['content']];
                }
                // 发送图片
                if($data['type'] == 'image'){
                    $data['media_id'] = (new Attachment)->getMedia_id($data['image'],$param['wechatId']);
                    if(!empty($data['media_id'])){
                        $mess['images'] = ['media_ids'=>[$data['media_id']]];
                    }
                }
                // 图文
                if($data['type'] == 'mpnews'){
                    $row = Materials::where('id',$data['material_id'])->find();
                    if(empty($news)){
                        \app\common\model\Logs::addLog("发送图文消息失败",['errmsg'=>'图文信息不存在'],$param['wechat_id'],"async/message");
                    }
                    $result = (new \app\common\logic\Wechat)->uploadmpnews($data['material_id'],$param['wechatId']);
                    if(isset($result['code']) && $result['code'] == -1){
                        \app\common\model\Logs::addLog("发送%s消息失败",$result,$param['wechat_id'],"async/menu");
                    }
                    $mess['mpnews'] = ['media_id'=>$result];
                }
                Db::startTrans();
                try{
                    $id = Messages::insert($data,false,true);
                    $result = (new \app\common\logic\Wechat)->weObj($param['wechatId'])->sendGroupMassMessage($mess);
                    if(!$result || (isset($result['errcode']) && $result['errcode'] == -1)){
                        Db::rollback();
                        \app\common\model\Logs::addLog("发送%s消息失败",$result,$param['wechat_id'],"async/menu");
                    }
                }catch (\think\Exception $e){
                    Db::rollback();
                    \app\common\model\Logs::addLog("发送%s消息失败",$e->getMessage(),$param['wechat_id'],"async/message");
                }
                Db::commit();
            }
        }
        die('FINISH...');
    }
}
